package com.itheima.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
public class AliOSSUtils {
//    @Value("${aliyun.oss.endpoint}")
//    String endpoint;
//
//    @Value("${aliyun.oss.bucketName}")
//    String bucketName;

    @Autowired
    private AliOSSProperties aliOSSProperties;

    public String upload(MultipartFile multipartFile) throws ClientException, IOException {
        String endpoint = aliOSSProperties.getEndpoint();
        String bucketName = aliOSSProperties.getBucketName();

        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 文件上传到阿里云后的名称
        String originalFilename = multipartFile.getOriginalFilename();
        String objectName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));

        // 获取要上传文件的字节输入流对象
        InputStream is = multipartFile.getInputStream();

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        try {
            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, is);

            // 上传文件
            ossClient.putObject(putObjectRequest);

            // 拼接文件上传后的url并返回
            // https://java416.oss-cn-beijing.aliyuncs.com/baby.jpg
            return endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + objectName;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
